package com.zhuo.project.order.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.zhuo.common.enums.SendStatus;
import com.zhuo.common.utils.SecurityUtils;
import com.zhuo.framework.aspectj.lang.annotation.Log;
import com.zhuo.framework.aspectj.lang.enums.BusinessType;
import com.zhuo.project.k3.domain.ZzMaterial;
import com.zhuo.project.k3.domain.ZzMaterialBarcode;
import com.zhuo.project.k3.service.IZzMaterialBarcodeService;
import com.zhuo.project.k3.service.IZzMaterialService;
import com.zhuo.project.order.domain.ZzDiagnoseDetail;
import com.zhuo.project.order.domain.ZzDiagnoseSend;
import com.zhuo.project.order.service.IZzDiagnoseDetailService;
import com.zhuo.framework.web.controller.BaseController;
import com.zhuo.framework.web.domain.AjaxResult;
import com.zhuo.common.utils.poi.ExcelUtil;
import com.zhuo.framework.web.page.TableDataInfo;
import com.zhuo.project.order.service.IZzDiagnoseSendService;
import com.zhuo.project.system.domain.SysUser;
import com.zhuo.project.system.service.ISysUserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * 处方单明细Controller
 *
 * @author zhuo
 * @date 2020-03-26
 */
@Api("处方单明细操作")
@RestController
@RequestMapping("/order/detail")
public class ZzDiagnoseDetailController extends BaseController {
    @Autowired
    private IZzDiagnoseDetailService zzDiagnoseDetailService;

    @Autowired
    private IZzMaterialBarcodeService iZzMaterialBarcodeService;

    @Autowired
    private IZzMaterialService iZzMaterialService;

    @Autowired
    private IZzDiagnoseSendService iZzDiagnoseSendService;

    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private IZzDiagnoseSendService zzDiagnoseSendService;

    /**
     * 查询处方单明细列表
     */
    @PreAuthorize("@ss.hasPermi('order:detail:list')")
    @GetMapping("/list")
    public TableDataInfo list(ZzDiagnoseDetail zzDiagnoseDetail) {
        startPage();
        List<ZzDiagnoseDetail> list = zzDiagnoseDetailService.selectZzDiagnoseDetailList(zzDiagnoseDetail);
        return getDataTable(list);
    }

    /**
     * 查询处方单明细列表
     */
    @ApiOperation("获取处方商品明细列表")
    @ApiImplicitParam(name = "diagnoseId", value = "处方ID", required = true, dataType = "String", paramType = "path")
    @PreAuthorize("@ss.hasPermi('order:head:list')")
    @GetMapping("/list/{diagnoseId}")
    public AjaxResult detailList(@PathVariable("diagnoseId") String diagnoseId) {

        ZzDiagnoseDetail zzDiagnoseDetail = new ZzDiagnoseDetail();
        zzDiagnoseDetail.setDiagnoseId(diagnoseId);
        List<ZzDiagnoseDetail> list = zzDiagnoseDetailService.selectZzDiagnoseDetailList(zzDiagnoseDetail);
        //  标识颜色
        Map<String, Double> calColor = new HashMap<>();
        for (ZzDiagnoseDetail detail : list) {
            if (calColor.containsKey(detail.getMaterialId())) {
                Double moreSendQty = calColor.get(detail.getMaterialId()) + detail.getQty() - detail.getTotalSendQty();
                calColor.put(detail.getMaterialId(), moreSendQty);
            } else {
                calColor.put(detail.getMaterialId(), detail.getQty() - detail.getTotalSendQty());
            }
        }
        for (ZzDiagnoseDetail detail : list) {
            String materialId = detail.getMaterialId();
            if (calColor.get(materialId).compareTo(0.0) == 0) {
                detail.setColor(0);
            } else if (calColor.get(materialId).compareTo(0.0) > 0) {
                detail.setColor(1);
            } else {
                detail.setColor(2);
            }
        }
        return AjaxResult.success(list);
    }

    /**
     * 导出处方单明细列表
     */
    @ApiOperation("导出处方明细")
    @ApiImplicitParam(name = "zzDiagnoseDetail", value = "导出处方明细", dataType = "ZzDiagnoseDetail")
    @PreAuthorize("@ss.hasPermi('order:head:list')")
    @Log(title = "处方单明细", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(ZzDiagnoseDetail zzDiagnoseDetail) {
        List<ZzDiagnoseDetail> list = zzDiagnoseDetailService.selectZzDiagnoseDetailList(zzDiagnoseDetail);
        ExcelUtil<ZzDiagnoseDetail> util = new ExcelUtil<ZzDiagnoseDetail>(ZzDiagnoseDetail.class);
        return util.exportExcel(list, "detail");
    }

    @ApiOperation("获取手工发药商品信息列表")
    @ApiImplicitParam(name = "diagnoseId", value = "diagnoseId", required = true, dataType = "String", paramType =
            "path")
    @PreAuthorize("@ss.hasPermi('order:head:list')")
    @GetMapping(value = "/{diagnoseId}/material/list")
    public AjaxResult getMaterialInfoList(@PathVariable("diagnoseId") String diagnoseId) {
        ZzDiagnoseDetail zzDiagnoseDetailSearch = new ZzDiagnoseDetail();
        zzDiagnoseDetailSearch.setDiagnoseId(diagnoseId);
        List<ZzDiagnoseDetail> list = zzDiagnoseDetailService.selectZzDiagnoseDetailList(zzDiagnoseDetailSearch);
        if (null == list || list.size() == 0) {
            return AjaxResult.error("3007", "处方不存在");
        }

        /* 判断这期间是否有其它人在操作配药 */
        ZzDiagnoseSend zzDiagnoseSendSearch = new ZzDiagnoseSend();
        zzDiagnoseSendSearch.setDiagnoseId(diagnoseId);
        zzDiagnoseSendSearch.setSendStatus(SendStatus.EQUIP.getCode());
        List<ZzDiagnoseSend> zzDiagnoseSendListSearch =
                zzDiagnoseSendService.selectZzDiagnoseSendList(zzDiagnoseSendSearch);

        String userName = SecurityUtils.getUsername();
        for (ZzDiagnoseSend zzDiagnoseSend : zzDiagnoseSendListSearch) {
            if (!userName.equals(zzDiagnoseSend.getEquipBy())) {
                SysUser sysUser = iSysUserService.selectUserByUserName(zzDiagnoseSend.getEquipBy());
                return AjaxResult.error(3013,
                        sysUser.getDept().getDeptName() + " 员工编号:" + sysUser.getUserName() + " 姓名:" + sysUser
                                .getNickName() + "正在操作配药，请勿操作");
            }
        }

        /* 合并相同行项目的数量汇总  */
        Map<String, Double> qtyMap = new HashMap<>(list.size());
        Map<String, Double> totalSendQtyMap = new HashMap<>(list.size());
        for (ZzDiagnoseDetail detail : list) {
            String materialId = detail.getMaterialId();
            if (qtyMap.containsKey(materialId)) {
                qtyMap.put(materialId, qtyMap.get(materialId) + detail.getQty());
            }else{
                qtyMap.put(materialId, detail.getQty());
            }

            if (totalSendQtyMap.containsKey(materialId)) {
                totalSendQtyMap.put(materialId, totalSendQtyMap.get(materialId) + detail.getTotalSendQty());
            }else{
                totalSendQtyMap.put(materialId, detail.getTotalSendQty());
            }
        }


        /* 获取已配数量 */
        Map<String, Double> equitQtyMap = new HashMap<>(zzDiagnoseSendListSearch.size());
        for (ZzDiagnoseSend zzDiagnoseSend : zzDiagnoseSendListSearch) {
            String materialId = zzDiagnoseSend.getMaterialId();
            if (equitQtyMap.containsKey(materialId)) {
                equitQtyMap.put(materialId, equitQtyMap.get(materialId) + zzDiagnoseSend.getSendQty());
            }else{
                equitQtyMap.put(materialId, zzDiagnoseSend.getSendQty());
            }
        }

        /*合并行项目展示 */
        List<ZzDiagnoseDetail> materialList = new ArrayList<>(list.size());
        for (ZzDiagnoseDetail detail : list) {
            if(!materialList.contains(detail)){
                if(null != equitQtyMap.get(detail.getMaterialId())){
                    detail.setSendQty(equitQtyMap.get(detail.getMaterialId()));
                }else {
                    detail.setSendQty(0.0);
                }
                detail.setQty(qtyMap.get(detail.getMaterialId()));
                detail.setTotalSendQty(totalSendQtyMap.get(detail.getMaterialId()));
                Double leftSendQty = detail.getQty() - detail.getTotalSendQty() - detail.getSendQty();
                if (leftSendQty.compareTo(0.0) == 0) {
                    detail.setColor(0);
                } else if (leftSendQty.compareTo(0.0) > 0) {
                    detail.setColor(1);
                } else {
                    detail.setColor(2);
                }
                materialList.add(detail);
            }
        }
        return AjaxResult.success(materialList);
    }


    @ApiOperation("获取商品信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "diagnoseId", value = "diagnoseId", required = true, dataType = "String",
                    paramType = "path"),
            @ApiImplicitParam(name = "barcode", value = "barcode", required = true, dataType =
                    "String", paramType = "path")})
    @PreAuthorize("@ss.hasPermi('order:head:list')")
    @GetMapping(value = "/{diagnoseId}/material/{barcode}")
    public AjaxResult getMaterialInfo(@PathVariable("diagnoseId") String diagnoseId,
            @PathVariable("barcode") String barcode) {
        ZzMaterialBarcode zzMaterialBarcode = iZzMaterialBarcodeService.selectZzMaterialBarcodeByBarCode(barcode);
        if (null == zzMaterialBarcode) {
            return AjaxResult.error(3010,"条形不存在");
        }
        String fmaterialid = zzMaterialBarcode.getFmaterialid();
        ZzMaterial zzMaterial = iZzMaterialService.selectZzMaterialByMaterialId(fmaterialid);
        if (null == zzMaterial) {
            return AjaxResult.error(3011,"商品不存在");
        }

        ZzDiagnoseDetail zzDiagnoseDetail = new ZzDiagnoseDetail();
        zzDiagnoseDetail.setDiagnoseId(diagnoseId);
        zzDiagnoseDetail.setMaterialId(fmaterialid);
        List<ZzDiagnoseDetail> list = zzDiagnoseDetailService.selectZzDiagnoseDetailList(zzDiagnoseDetail);
        if (null == list || list.size() == 0) {
            return AjaxResult.error(3012,"处方不存在此商品");
        }

        double leftSendQty = 0.0;
        for (ZzDiagnoseDetail detail : list) {
            leftSendQty = leftSendQty + detail.getQty() - detail.getTotalSendQty();
        }

        ZzDiagnoseSend zzDiagnoseSendSearch = new ZzDiagnoseSend();
        zzDiagnoseSendSearch.setDiagnoseId(diagnoseId);
        zzDiagnoseSendSearch.setMaterialId(fmaterialid);
        zzDiagnoseSendSearch.setSendStatus(SendStatus.EQUIP.getCode());

        List<ZzDiagnoseSend> zzDiagnoseSendList = iZzDiagnoseSendService.selectZzDiagnoseSendList(zzDiagnoseSendSearch);
        double equitQty = 0.0;
        for (ZzDiagnoseSend zzDiagnoseSend : zzDiagnoseSendList) {
            equitQty = equitQty + zzDiagnoseSend.getSendQty();
        }

        Double scanNumPer = zzMaterial.getfUnDecimal1();

        ZzDiagnoseSend zzDiagnoseSend = new ZzDiagnoseSend();
        zzDiagnoseSend.setDiagnoseId(diagnoseId);
        zzDiagnoseSend.setMaterialId(fmaterialid);
        zzDiagnoseSend.setMaterialName(zzMaterial.getFname());
        zzDiagnoseSend.setBarcode(zzMaterial.getfUnText());
        zzDiagnoseSend.setSendQty(equitQty);
        zzDiagnoseSend.setLeftSendQty(leftSendQty);
        zzDiagnoseSend.setScanNumPer(scanNumPer);
        zzDiagnoseSend.setLastEquipTime(new Date());
        zzDiagnoseSend.setError("");


        return AjaxResult.success(zzDiagnoseSend);
    }


    /**
     * 获取处方单明细详细信息
     */
    @PreAuthorize("@ss.hasPermi('order:detail:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(zzDiagnoseDetailService.selectZzDiagnoseDetailById(id));
    }

    /**
     * 新增处方单明细
     */
    @PreAuthorize("@ss.hasPermi('order:detail:add')")
    @Log(title = "处方单明细", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ZzDiagnoseDetail zzDiagnoseDetail) {
        return toAjax(zzDiagnoseDetailService.insertZzDiagnoseDetail(zzDiagnoseDetail));
    }

    /**
     * 修改处方单明细
     */
    @PreAuthorize("@ss.hasPermi('order:detail:edit')")
    @Log(title = "处方单明细", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ZzDiagnoseDetail zzDiagnoseDetail) {
        return toAjax(zzDiagnoseDetailService.updateZzDiagnoseDetail(zzDiagnoseDetail));
    }

    /**
     * 删除处方单明细
     */
    @PreAuthorize("@ss.hasPermi('order:detail:remove')")
    @Log(title = "处方单明细", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(zzDiagnoseDetailService.deleteZzDiagnoseDetailByIds(ids));
    }
}
